---
import { type MarkdownHeading } from "astro";

import { getIsRtlFromUrl } from "../../languages";

export interface Props {
  headings: MarkdownHeading[];
  title: string;
}

let { headings, title } = Astro.props;
headings = [{ depth: 2, slug: "overview", text: title }, ...headings].filter(
  ({ depth }) => depth > 1 && depth < 4,
);

const { pathname } = Astro.url;
const isRtl = getIsRtlFromUrl(pathname);
---

<div dir={isRtl ? "rtl" : "ltr"}>
  <h2
    class="mb-4 text-lg font-semibold text-slate-900 dark:text-t3-purple-50"
    id="toc-heading"
  >
    On this page
  </h2>
  <ul class="mb-4 w-full list-none marker:text-t3-purple-300">
    {
      headings.map((heading) => {
        const { depth, slug, text } = heading;

        //add data-component-type to headings to be able to filter them in the sidebar
        let dataComponentType = "";
        switch (text) {
          case "prisma":
            dataComponentType = "prisma";
            break;
          case "src/types":
          case "src/server/auth.ts":
            dataComponentType = "nextauth";
            break;
          case "postcss.config.js":
          case "prettier.config.mjs":
            dataComponentType = "tailwind";
            break;
          case "src/server/api":
          case "src/server/api/routers":
          case "src/utils":
            dataComponentType = "trpc";
            break;
        }

        return (
          <li
            data-components={dataComponentType || null}
            class:list={[
              "w-full list-none border-t3-purple-300/20 p-1 text-sm transition-colors duration-300 hover:border-t3-purple-300/50",
              isRtl
                ? ["border-r-2", depth === 2 ? "pr-2" : "pr-4"]
                : ["border-l-2", depth === 2 ? "pl-2" : "pl-4"],
            ]}
          >
            <a
              class="text-t3-purple-800 hover:text-t3-purple-400 dark:text-t3-purple-200 dark:hover:text-t3-purple-100"
              href={`#${slug}`}
            >
              {text}
            </a>
          </li>
        );
      })
    }
  </ul>
</div>

<script is:inline>
  // Toggle classes when items are in view
  document.querySelectorAll("article :is(h1,h2,h3)").forEach((h) => {
    new IntersectionObserver(
      (entries) => {
        entries.forEach((entry) => {
          const id = entry.target.id;
          // have to do "All" here cause we render this component in pageContent for mobile too
          const tocItem = Array.from(
            document.querySelectorAll(`a[href="#${id}"]`),
          ).at(-1);
          // this occurs when the id = "toc-heading"
          if (!tocItem) return;

          if (entry.isIntersecting) {
            // get current all active elements
            const currentActiveElements = Array.from(
              document.querySelectorAll(
                `[data-current-active-tab-content-item="true"]`,
              ),
            );

            // get current all parent active elements
            const currentActiveParentElements = Array.from(
              document.querySelectorAll(
                `[data-current-active-parent-tab-content-item="true"]`,
              ),
            );

            // if has active elements
            if (currentActiveElements.length) {
              // loop through all elements and remove class and attr
              for (const el of currentActiveElements) {
                el.classList.remove(
                  "font-medium",
                  "bg-t3-purple-300/20",
                  "text-t3-purple-700",
                  "dark:text-t3-purple-100",
                );
                el.removeAttribute("data-current-active-tab-content-item");
              }
            }
            // if has active parent elements
            if (currentActiveParentElements.length) {
              // loop through all parent elements and remove class and attr
              for (const parentEl of currentActiveParentElements) {
                parentEl.classList.remove(
                  "dark:bg-t3-purple-300/20",
                  "bg-t3-purple-300/30",
                  "border-t3-purple-300/100",
                );
                parentEl.removeAttribute(
                  "data-current-active-parent-tab-content-item",
                );
              }
            }

            tocItem.classList.add(
              "font-medium",
              "text-t3-purple-700",
              "dark:text-t3-purple-100",
            );
            tocItem.parentElement.classList.add(
              "border-t3-purple-300/100",
              "dark:bg-t3-purple-300/20",
              "bg-t3-purple-300/30",
            );
            // set data attr to active element also will helpful when need to remove active state
            tocItem.setAttribute("data-current-active-tab-content-item", true);
            tocItem.parentElement.setAttribute(
              "data-current-active-parent-tab-content-item",
              true,
            );
          }
        });
      },
      {
        rootMargin: "-100px 0% -66%",
        threshold: 1,
      },
    ).observe(h);
  });
</script>
